import FormConstant from "./FormConstant";
import { Dialog, Util } from '@lowcode/jpaas-common-lib';
import FormApi from "./api/FormApi";
import rxSubExcelImport from "./common/rxSubExcelImport";

import {I18Parse,CommonLang} from '@lowcode/jpaas-common-lib';
import jsCompsLang from '../../../../../locales/lang/impl/form/jsCompsLang';
let lang = jsCompsLang;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.jsCompsLang,langKey, text)
}

var SubtableFunc={};

/**
 * 删除子表记录
 * @param tablename
 * @param mode
 * @param tableLabel
 * @param idx
 */
SubtableFunc.remove=function(tablename, mode, tableLabel, idx) {
    var ary = this.data[FormConstant.SubPrefix + tablename];
    var self_=this;


    this.$confirm({
        content: this.$ti18('rxMsa.delCurrentInfo',"您确定要删除当前项吗?"),
        zIndex:40000,
        okText: this.$ti18('rxForm.okBtn','确定'),
        cancelText: this.$ti18('rxForm.cancelBtn','取消'),
        onOk() {
            var rows=[];
            if(mode=="block"){
                var row=ary[idx];
                rows.push(row);
            }
            else{
                var selRows= ary.filter(item=>{
                    return item.selected==true;
                });
                rows.push(...selRows);
            }

            if(self_.beforeRemove){
                var rtn=self_.beforeRemove(tablename,rows);
                if(rtn && !rtn.success){
                    self_.$message.warning(rtn.msg);
                    return;
                }
            }
            //点击确定回调；
            if (mode == "block") {
                if (ary.length == 0) {
                    return;
                }
                ary.splice(idx, 1);
            } else {
                for (var i = ary.length - 1; i >= 0; i--) {
                    var o = ary[i];
                    if (o.selected) {
                        ary.splice(i, 1);
                    }
                }
            }
            self_.$forceUpdate()
        }
    });
}

SubtableFunc.up=function(tablename, mode, tableLabel, idx) {
    var ary = this.data[FormConstant.SubPrefix + tablename];
    if (mode == "block") {
        //块模式下的子表
        if (idx == 0) {
            this.$message.warning("亲~我已经上不去了啦");
            return;
        }
        var before = ary[idx - 1];
        var after = ary[idx];
        ary.splice(idx - 1, 1, after);
        ary.splice(idx, 1, before);
    } else {

        if (ary.length <= 1) {
            return;
        }
        if (ary[0].selected) {
            this.$message.warning("已经到顶了")
            return;
        }
        for (var i = 0; i < ary.length; i++) {
            if (ary[i].selected) {
                ary[i - 1] = ary.splice(i, 1, ary[i - 1])[0];
            }
        }
    }
}

SubtableFunc.down=function(tablename, mode, tableLabel, idx) {

    var ary = this.data[FormConstant.SubPrefix + tablename];
    if (mode == "block") {
        //块模式下的子表
        if (idx == ary.length - 1) {
            this.$message.warning("亲~我已经下不去了啦")
            return;
        }
        var before = ary[idx];
        var after = ary[idx + 1];
        ary.splice(idx + 1, 1, before);
        ary.splice(idx, 1, after);

    } else {

        if (ary.length <= 1) {
            return;
        }
        if (ary[ary.length - 1].selected) {
            this.$message.warning("已经到底了");
            return;
        }

        for (var i = ary.length - 1; i >= 0; i--) {
            if (ary[i].selected) {
                ary[i + 1] = ary.splice(i, 1, ary[i + 1])[0];
            }
        }

    }

}

/**
 * 处理EXCEL导入数据。
 * @param data
 *  {tablename:tablename,singles:singles,fieldsData: listData}
 */
SubtableFunc.handData=function (data) {

    //子表中的数据
    var subData = this.data[FormConstant.SubPrefix + data.tablename];
    //导入的数据
    var fieldsData = data.fieldsData;
    //需要去重复的字段
    var singles = data.singles;

    if (singles.length > 0) {
        for (var i = 0; i < singles.length; i++) {
            var fieldName = singles[i];
            fieldsData = this.removDuplicates(fieldsData, subData, fieldName);
        }
        this.data[FormConstant.SubPrefix + data.tablename] = fieldsData;
    } else {
        this.data[FormConstant.SubPrefix + data.tablename].push(...data.fieldsData);
    }
}

//去除重复数据
SubtableFunc.removDuplicates=function(data, subData, fieldName) {
    //子表中无数据情况
    if (subData.length == 0) {
        for (var i = 0; i < data.length; i++) {
            var value = data[i][fieldName];
            const target = subData.find(item => item[fieldName] === value);
            if (!target) {
                subData.push(data[i]);
            }
        }
        return subData;
    } else {
        var newData = [];
        for (var i = 0; i < data.length; i++) {
            var value = data[i][fieldName];
            const target = newData.find(item => item[fieldName] === value);
            if (!target) {
                newData.push(data[i]);
            }
        }
        return newData;
    }
}

/**
 * 打开定义对话框。
 * @param tablename
 * @param alias
 */
SubtableFunc.customDialog=function (tablename,alias) {
    var btn=this.getTableButton(tablename,alias);
    if(!btn){
        this.$message.warning(this.i18n('tip.notconfigDialog','没有找到配置自定义对话框!'));
        return;
    }
    var binding=JSON.parse( btn.conf);

    var dialogalias = binding.dialogalias;
    var gridInput = binding.gridInput;
    //构建查询条件。
    var params =  this.getParamsInput(gridInput);

    //多选还是单选
    var single=binding.dialogType=='single';
    params.single=single;
    var parameter = {
        key: dialogalias,
        params:Object.keys(params).map(function (key) {
            return key + "=" + params[key];
        }).join("&")
    }
    var self_=this;

    Dialog.dialog(parameter, {curVm: this},function(data) {
        var rows = data.rows;
        if(!rows){
            rows=data;
        }

        if(!(rows instanceof Array)) rows = [rows];


        //绑定映射行
        self_.bindRows(binding,rows,tablename);
    })
}

/**
 * 获取子表按钮
 * @param tablename 子表名称
 * @param alias     按钮别名
 * @returns {null|*}
 */
SubtableFunc.getTableButton=function (tablename,alias) {
    var json=this.getTableMeta(tablename);

    if(json==null){
        return null;
    }
    var buttons=json.buttons;

    for(var i=0;i<buttons.length;i++){
        var btn=buttons[i];
        if(btn.alias==alias){
            return btn;
        }
    }
    return null;
}

/**
 * 获取子表元数据。
 * @param tablename
 * @returns {null|*}
 */
SubtableFunc.getTableMeta=function (tablename) {
    //metadata
    for(var key in this.metadata){
        var json=this.metadata[key];
        if(json.ctltype=="rx-table" && json.name==tablename){
            return json;
        }
    }
    return null;
}


/**
 * 构造对话框参数。
 * @param gridInput
 * @returns {{}}
 */
SubtableFunc.getParamsInput=function(gridInput) {
    if(!gridInput || gridInput.length == 0) return {};

    var param = {};
    for(let i = 0, j = gridInput.length; i < j; i++) {
        var obj = gridInput[i];
        var bindVal = obj.bindVal;
        var valmode = obj.valmode;

        var mode=obj.mappingMode;
        var val="";
        if(mode=="mapping"){
            val=this.data[bindVal];
        }
        else{
            val= eval('(function() {' + bindVal + '}())');;
        }

        if(!val) { //父联动字段为空
            delete param[obj.field];
        } else {
            if(mode=="mapping"){
                if(valmode=="single"){
                    param[obj.field]=val;
                }
                else{
                    var json=JSON.parse(val)
                    param[obj.field]=json.value;
                }
            }
            else{
                param[obj.field]=val;
            }
        }
    }
    return param;
}

/**
 * 数据绑定到子表。
 * @param binding
 * @param rows
 * @param tablename
 */
SubtableFunc.bindRows=function(binding,rows,tablename){
    var returnFields = binding.returnFields;
    if(!returnFields || returnFields.length==0){
        return;
    }

    var uniqueField=binding.uniqueField;
    var subTableData=this.data[FormConstant.SubPrefix + tablename];
    //一对多子表
    var aryTmp=[];

    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        var newRow = this.handOneRow(row, returnFields);
        var canAdd = this.canAddRow(uniqueField, newRow, subTableData);
        if (!canAdd) {
            continue;
        }
        newRow.index_ = Util.randomId();
        newRow.selected = false;
        aryTmp.push(newRow);
    }

    var self_=this;

    if(binding.callback){
        var method="self_.func_" +binding.callback +"(aryTmp,tablename)"
        var rtn=eval(method);
        if(rtn && !rtn.success){
            self_.$message.warning(rtn.msg);
            return;
        }
    }

    subTableData.push(...aryTmp);
}

/**
 * 处理绑定一行数据。
 * @param rtnRow
 * @param returnFields
 */
SubtableFunc.handOneRow=function(rtnRow,returnFields){
    var newRow={};
    for(var k = 0, l = returnFields.length; k < l; k++) {
        var field = returnFields[k];
        var valmode=field.valmode;
        var bindField=field.bindField;

        if(valmode=="double"){
            var json={};
            json.label=rtnRow[field.returnLabel.toUpperCase()];
            json.value=rtnRow[field.returnValue.toUpperCase()];
            newRow[bindField]= JSON.stringify(json) ;
        }else{
            newRow[bindField]=rtnRow[field.returnValue.toUpperCase()];
        }
    }

    return newRow;
}

/**
 * 判断一行是否运行添加。
 * @param uniqueField
 * @param newRow
 * @param subTableData
 * @returns {boolean}
 */
SubtableFunc.canAddRow=function(uniqueField,newRow,subTableData){
    if(!uniqueField){
        return true;
    }
    var val=newRow[uniqueField];
    var ary= subTableData.filter(item=>{
        return item[uniqueField]==val;
    });
    if(ary.length==0){
        return true;
    }
    return false;
}


/**
 * excel 导入
 * @param tablename     表名
 * @param alias         按钮别名
 */
SubtableFunc.excelImport=function(tablename,alias){

    var tableMeta=this.getTableMeta(tablename);

    var btn=this.getTableButton(tablename,alias);
    if(!btn){
        this.$message.warning(this.i18n('tip.notconfig','没有找到配置!'));
        return;
    }
    var config=btn.conf;
    if(!config){
        this.$notification["error"]({
            message: this.$ti18('rxMsa.actionTips','操作提示'),
            description:
                this.i18n('tip.subExcelMapping','子表Excel映射未配置!'),
        });
        return;
    }
    var fieldsConfig=JSON.parse(config);
    var conf = {
        component:rxSubExcelImport,
        title: this.i18n('tip.subExcelImport','子表Excel导入!'),
        curVm: this,
        data: {
            fieldsConfig:fieldsConfig,
            comment:tableMeta.comment
        },
        widthHeight: ['750px', '500px']
    };
    var self_=this;
    Util.open(conf, function(action,data) {
        if(action != 'ok') {
            return;
        }
        var fields=fieldsConfig.fields;
        var listData=[];
        for(var i=0;i<data.length;i++){
            var obj={};
            obj.selected=false;
            for(var j=0;j<fields.length;j++){
                var name=fields[j].name;
                var startColumn=fields[j].startColumn;
                var value=data[i][startColumn-1];
                obj[name]=value;
            }
            obj.index_=Util.randomId();
            listData.push(obj);
        }
        var singles=[];
        //获取需唯一的字段
        for(var j=0;j<fields.length;j++){
            if(fields[j].single){
                singles.push(fields[j].name);
            }
        }
        var data={tablename:tablename,singles:singles,fieldsData: listData};
        self_.handData(data)

    });
}


/**
 * excel 下载数据。
 * @param tablename
 * @param alias
 */
SubtableFunc.excelExport=function(tablename,alias){
    //{"sheetNo":1,"fields":[{"comment":"A","name":"A","type":"varchar"},{"comment":"B","name":"B","type":"varchar"}]}

    var btn=this.getTableButton(tablename,alias);
    if(!btn){
        this.$message.warning(this.i18n('tip.notconfig','没有找到配置!'));
        return;
    }
    var tableMeta=this.getTableMeta(tablename);
    var config=btn.conf;

    var subData = this.data[FormConstant.SubPrefix + tablename];
    var subDataStr="[]";
    if(subData){
        subDataStr=JSON.stringify(subData);
    }



    if(config) {
        var fieldsConfig = JSON.parse(config);
        if(!fieldsConfig.fileId){
            this.$message.warning(this.i18n('tip.uploadExportTemp','请上传导出模板！'));
            return;
        }
        FormApi.exportExcel({
            fieldsConfig: config,
            comment: tableMeta.comment,
            subData: subDataStr
        }).then(res => {
            let blob = new Blob([res], {
                type: 'application/vnd.ms-excel'
            });
            let fileName = tableMeta.comment + this.i18n('tip.SubtableExportData','子表导出数据')+'.xlsx';
            if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(blob, fileName);
            } else {
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = fileName;
                link.click();
                //释放内存
                window.URL.revokeObjectURL(link.href)
            }
        });
    }
}

export  default  SubtableFunc;
